package me

import grails.converters.JSON
import groovy.sql.Sql
import groovy.json.*
import grails.gorm.*
import java.io.*
import java.util.UUID;
import org.springframework.messaging.simp.SimpMessageSendingOperations

class FileController {

	SimpMessageSendingOperations brokerMessagingTemplate


	def delFiles = {file->
		if (file!=null) {
			def files = File.findAllByParentFileId(file.id)
			println files
			files.each{
				delFiles(it)
			}
			file.delete(flush:true)
		}
	}

	def getTreeFile={id,meetingId->
        def results = []
        def subs = []
        if (id==null) {
            subs = File.findAll("from File where parentFileId is null and meetingId = :meetingId order by fileOrder asc,dateCreated",
            [meetingId:meetingId])
        } else {
            subs = File.findAll("from File where parentFileId=:parentFileId and meetingId = :meetingId  order by fileOrder asc,dateCreated",
            [parentFileId:id,meetingId:meetingId])
        }

        subs.each{
            def hm = [:]
            hm.id = it.id
            hm.cnName = it.cnName
			//hm.disCnName = it.password==null||it.password==""?it.cnName:it.cnName+"*"
			hm.password = it.password
            hm.fileUuid = it.fileUuid 
            hm.parentFileId = it.parentFileId
            hm.isDir = it.isDir
            hm.dateCreated = it.dateCreated
			hm.fileTypeId = it.fileTypeId
            hm.lastUpdated = it.lastUpdated
            hm.leaf = !it.isDir
            hm.children = getTreeFile(it.id,meetingId)
            results.add(hm)
        }
        return results
    }

    def index() {

    }


    def delete() {
    	def results = [success:true]
        def ids = (params.ids==null||params.ids=="")?"":params.ids

        ids.split(",").each{
    		def file = File.findById(it)
    		delFiles(file)
    		
	    	/*	def files = File.where {
	            meetingId == params.id
	        }.deleteAll()*/
    	}
		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'
    	render results  as JSON
    }

    def mkdir() {
    	def results = [success:true]
    	def parentFileId = (params.parentFileId==null||params.parentFileId=="")?null:(params.parentFileId as Long)
    	def file = new File(cnName:params.cnName,fileUuid:null,meetingId:params.meetingId,
    	parentFileId:parentFileId,isDir:true,fileOrder:10000,fileTypeId:null,password:null)
		file.save()
		results.id = file.id

		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'

		render results  as JSON
    }

    def updatefiletype() {
    	def results = [success:true]
		def ids = (params.ids==null||params.ids=="")?"":params.ids

		ids.split(",").each{
			println it
			def file = File.findById(it)
			file.fileTypeId = params.fileTypeId as Long
			file.save(failOnError: true,flush:true)

			/*	def files = File.where {
                meetingId == params.id
            }.deleteAll()*/
		}
		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'
		render results  as JSON

    }

    def movefile() {
    	def results = [success:true]
    	
    
		render results  as JSON

    }

    def sortfile() {
    	def results = [success:true]
		def ids = params.list('ids')
		def indexs =  params.list('indexs')


		ids.eachWithIndex{it,i->
			//println it + "   "+i
			def file = File.findById(it)
			file.fileOrder = indexs[i] as Integer
			file.save(flush:true)
		}
		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'
		render results  as JSON

    }


    def store() {
    	def results = getTreeFile(null,params.meetingId as Long)


        render results  as JSON

    }

	def gridstore() {

		def results = []

		results = File.findAll("from File where meetingId=? and isDir = 0",params.meetingId as Long)

		//results = [success:true,total:results.size(),results:results]
		render results  as JSON


	}


	def rename() {
		def results = [success:true]
		def file = File.findById(params.id)
		file.cnName = params.cnName+".pdf"
		file.save(failOnError: true,flush: true)
		results.id = file.id
		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'
		render results  as JSON
	}

	def setpassword() {
		def results = [success:true]
		def file = File.findById(params.id)
		file.password = params.password
		file.save(failOnError: true,flush: true)
		results.id = file.id
		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'
		render results  as JSON
	}

    def upload() {
    	def meetingId = params.meetingId==""?null:(params.meetingId as Long)
    	def parentFileId = params.parentFileId==""?null:(params.parentFileId as Long)
    	println params.meetingId
    	println params.parentFileId
    	String applicationPath = request.getSession().getServletContext().getRealPath("")
    	println applicationPath
    	request.getMultiFileMap().fileupload.each {
		    //println it.bytes.length
		    String fileUuid = UUID.randomUUID().toString()
    		String cnName = it.originalFilename
		    //String filepath =applicationPath+"\\pdf\\" + fileUuid;
			String filepath =applicationPath+"pdf/" + fileUuid+".pdf";
		    println filepath
		    def ioFile = new java.io.File(filepath);   
		    /*if(ioFile.exists()){   
		        ioFile.delete();   
		    } */ 
		    def fos = new FileOutputStream(ioFile);   
		    fos.write(it.bytes,0,it.bytes.length);   
		    fos.flush();   
		    fos.close(); 

		    def file = new File(cnName:cnName,fileUuid:fileUuid,meetingId:meetingId,parentFileId:parentFileId,
		    isDir:false,fileOrder:10000,fileTypeId:null,password:null)
		    file.save()
		}

		brokerMessagingTemplate.convertAndSend "/topic/notice", '{"flag":1}'

    	def results = [success:true]
    	render results  as JSON
    }
}
